const verify = {}
verify.isEmpty = (val, msg) => {
  let ischeck = !val || val == null || val == undefined;
	if (Array.isArray(val) && !val.length) {
		 ischeck = true
	} else if (typeof val == 'object' && !Object.keys(val).length) {
		 ischeck = true
	} else if (val+''.trim() == '') {
		 ischeck = true
	}
  if (ischeck) {
    uni.showToast({
      title: msg || '不能为空',
      icon: "none",
      duration: 2000
    })
  }
  return ischeck
}
verify.checkPhone = (val, msg) => {
  if (!val || val+''.trim() == '') {
    uni.showToast({
      title: '手机号不能为空',
      icon: "none",
      duration: 2000
    })
    return true
  }
  let myreg = /^[1][2,3,4,5,6,7,8,9][0-9]{9}$/;
  let ischeck = !myreg.test(val);
  if (ischeck) {
    uni.showToast({
      title: msg || '手机格式不正确',
      icon: "none",
      duration: 2000
    })
  }
  return ischeck
}


verify.checkCardNumber = (val, msg) => {
  // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (reg.test(val) === false) {
    uni.showToast({
      title: msg || '身份证号格式错误',
      icon: "none",
      duration: 2000
    })
    return true;
  }
  return false;
}

verify.checkRealName = (val, msg) => {
  var regName = /^[\u4e00-\u9fa5]{2,4}$/;
  if (!regName.test(val)) {
    uni.showToast({
      title: msg || '真实姓名填写有误',
      icon: "none",
      duration: 2000
    })
    return true;
  }
  return false;
}


verify.equles = (val1, val2, msg) => {
  let ischeck = val1 != val2;
  if (ischeck) {
    uni.showToast({
      title: msg || '两个值不相同',
      icon: "none",
      duration: 2000
    })
  }
  return ischeck
}

verify.checkLength = (val, length, msg) => {
  if (val.length < length) {
    uni.showToast({
      title: msg || '长度不能少于' + length + '位',
      icon: "none",
      duration: 2000
    })
    return true
  }
  return false
}

verify.checkPrivacy = (fun) => {
	let _this = this
	wx.getPrivacySetting({
		success: res => {
			if (res.needAuthorization) {
				EventBus.$on('privacyResult', (data) => {
					if (typeof fun == 'function') {
						fun()
					}
				})
				EventBus.$emit('openPrivacy')
			} else {
				if (typeof fun == 'function') {
					fun()
				}
			}
		}
	})
}

/**
 * 表单验证
 * 验证类型 
 * 	required-必填
 * 	phone-手机号
 */
verify.verifyForm = (form, rules) => {
	return new Promise((resolve, reject) => {
		let ruleKeys = Object.keys(rules)
		for (let ckey in ruleKeys) {
			let column = ruleKeys[ckey]
			let value = form[column]
			for (let rkey in rules[column]) {
				let rule = rules[column][rkey]
				if (rule.required && verify.isEmpty(value, rule.message)) {
					reject()
					return
				} else if (rule.phone && verify.checkPhone(value, rule.message)) {
					reject()
					return
				} else if (rule.pattern && !rule.pattern.test(value)) {
					uni.showToast({
					  title: rule.message || '格式错误',
					  icon: "none",
					  duration: 2000
					})
					reject()
					return
				}
			}
		}
		resolve()
	})
}
export default verify;
